<template>
  <div class="volume-control">
    <!-- 静音按钮 -->
    <button class="control-btn" @click="toggleMute">
      {{ isMuted ? '🔇' : volumeIcon }}
    </button>

    <!-- 音量条 -->
    <div class="volume-bar" @click="handleClick">
      <div
        class="volume-progress"
        :style="{ width: displayVolume * 100 + '%' }"
      ></div>
    </div>
  </div>
</template>

<script>
import { computed, ref } from "vue";

export default {
  name: "VolumeControl",
  props: {
    volume: {
      type: Number,
      required: true
    },
  },
  emits: ["volume-change"],
  setup(props, { emit }) {
    const isMuted = ref(false); // 是否静音
    const lastVolume = ref(props.volume); // 静音前的音量值

    // 计算显示的音量值
    const displayVolume = computed(() => {
      return isMuted.value ? 0 : props.volume;
    });

    // 音量图标
    const volumeIcon = computed(() => {
      if (isMuted.value) return '🔇';
      if (props.volume > 0.5) return '🔊';
      if (props.volume > 0) return '🔉';
      return '🔇';
    });

    // 切换静音状态
    const toggleMute = () => {
      if (isMuted.value) {
        // 如果当前是静音状态，恢复之前的音量
        emit("volume-change", lastVolume.value);
      } else {
        // 如果当前不是静音状态，记录当前音量并设置为静音
        lastVolume.value = props.volume;
        emit("volume-change", 0);
      }
      isMuted.value = !isMuted.value;
    };

    // 点击音量条时的处理逻辑
    const handleClick = (e) => {
      const bar = e.currentTarget;
      const clickPosition = e.clientX - bar.getBoundingClientRect().left;
      const barWidth = bar.clientWidth;
      const newVolume = clickPosition / barWidth;

      // 更新音量值
      emit("volume-change", newVolume);

      // 如果当前是静音状态，取消静音
      if (isMuted.value) {
        isMuted.value = false;
      }
    };

    return {
      isMuted,
      displayVolume,
      volumeIcon,
      toggleMute,
      handleClick
    };
  }
};
</script>
